/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbCloud			*/
/*	Author:		gong_libin			*/
/*	Date:		2012_01_10			*/
/*	File:		MrLock.h			*/
/********************************************************/

#ifndef _MRLOCK_H
#define	_MRLOCK_H

#include "MrGlobal.h"
#include <pthread.h>

class CMrLock
{
public:
	CMrLock() { m_pLock = NULL; }
	virtual ~CMrLock() { m_pLock = NULL; }

	virtual void MrLockFree()
	{
		if (NULL != m_pLock) {
			free(m_pLock);
			m_pLock = NULL;
		}

		return;
	}

	inline virtual int MrLockLock();
	inline virtual int MrLockUnlock();

	virtual int MrLockDelete() = 0;
	virtual int MrLockMalloc(void* pLock) = 0;
	virtual int MrLockCreate(bool bShared) = 0;
	virtual void* MrLockGetLock() { return m_pLock; }

protected:
	void* m_pLock;

private:

};

int CMrLock::MrLockLock()
{
	if (NULL != m_pLock) {
		if (MR_SUCCESS != pthread_mutex_lock((pthread_mutex_t*)m_pLock)) {
			MR_ERROR("%s\n", strerror(errno));
			return MR_FAILURE;
		}
	}
	else {
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrLock::MrLockUnlock()
{
	if (NULL != m_pLock) {
		if (MR_SUCCESS !=  pthread_mutex_unlock((pthread_mutex_t*)m_pLock)) {
			MR_ERROR("%s\n", strerror(errno));
			return MR_FAILURE;
		}
	}
	else {
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

#endif /* _MRLOCK_H */
